import 'dart:async';

/*
使用方法：
1、定义事件体
class MyEvent {
  final String content;
  MyEvent(this.content);
}
2、注册监听
myListen = EventManager.listen<MyEvent>((msg) {
    print(msg.content);
});
3、触发事件
EventManager.emit(MyEvent("Hello!"));
4、移除监听
myListen.cancel();
5、清空监听
EventManager.clear();
* */

class EventManager {
  static final _eventController = StreamController.broadcast();
  static final List<StreamSubscription> _subscriptions = [];

  /// 监听事件，返回 StreamSubscription 以便移除监听
  static StreamSubscription<T> listen<T>(void Function(T event) onData) {
    final subscription = _eventController.stream.where((event) => event is T).cast<T>().listen(onData);
    _subscriptions.add(subscription);
    return subscription;
  }

  /// 触发事件
  static void emit<T>(T event) {
    _eventController.add(event);
  }

  /// 清空监听
  static void clear() {
    for (var subscription in _subscriptions) {
      subscription.cancel();
    }
    _subscriptions.clear();
  }
}